/**
 * 
 */
package leetCode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

/**
 * @author zhong
 *
 */
public class CustomSortString {
	public String customSortString(String S, String T) {
		Character[] arr = new Character[T.length()];
		for (int i = 0; i < T.length(); i++) {
			arr[i] = T.charAt(i);
		}
		Arrays.sort(arr, new Comparator<Character>() {
			@Override
			public int compare(Character a, Character b) {
				System.out.println(a + " " + b);
				if (a == b) {
					return 0;
				} else {
					int a1 = S.indexOf(a);
					int b1 = S.indexOf(b);
					if (a1 >= 0 && b1 >= 0) {// 两个都存在
						if (a1 > b1) {
							return 1;
						} else {
							return -1;
						}
					} else if (a1 >= 0) {
						return 1;
					} else if (b1 >= 0) {
						return -1;
					} else {
						return 0;// 都没出现，地位相等
					}
				}
			}
		});
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			char ch = arr[i];
			sb.append(ch);
		}
		return sb.toString();
	}

	public String customSortString1(String S, String T) {
		HashMap<Character, Integer> str2int = new HashMap<>(26);
		HashMap<Integer, Character> int2str = new HashMap<>(26);
		for (int i = 0; i < S.length(); i++) {
			char ch = S.charAt(i);
			str2int.put(ch, i);
			int2str.put(i, ch);
		}
		int k = S.length();
		for (char ch = 'a'; ch <= 'z'; ch++) {
			if (!str2int.containsKey(ch)) {
				str2int.put(ch, k);
				int2str.put(k++, ch);
			}
		}
		// 把T转化成int的list，并排序
		int[] arr = new int[T.length()];
		for (int i = 0; i < T.length(); i++) {
			arr[i] = str2int.get(T.charAt(i));
		}
		Arrays.sort(arr);
		StringBuilder sBuilder = new StringBuilder(T.length());
		for (int i : arr) {
			sBuilder.append(int2str.get(i));
		}
		return sBuilder.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String S = "awjeuldzxknyocsrfpvq";
		String T = "itnmbfynwuktoeulvfrjowqqnburnvendrafgfcgjiaovffzoxocsonpxmuqfhluzhaiuvldldvrcvofsfnaqfxrdnkvoguxqbke";
		System.out.println(new CustomSortString().customSortString(S, T));
	}

}
